package handlers

import (
	"net/http"
	"strings"
	"supply-chain/models"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ManufacturerHandler struct {
	DB *gorm.DB
}

type ProductRequest struct {
	ProductName string `json:"product_name" binding:"required"`
}

type ProductResponse struct {
	EPCID string `json:"epc_id"`
}

// RequestMaterial 处理原材料请求
func (h *ManufacturerHandler) RequestMaterial(c *gin.Context) {
	var request ProductRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查产品是否在支持列表中
	requiredMaterials, exists := models.ProductMaterialMap[request.ProductName]
	if !exists {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的产品类型"})
		return
	}

	// 查找所有需要的原材料
	var materials []models.Material
	for _, materialName := range requiredMaterials {
		var material models.Material
		if err := h.DB.Where("status = ? AND name = ?", "in_stock", materialName).First(&material).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "缺少所需原材料: " + materialName})
			return
		}
		materials = append(materials, material)
	}

	// 更新所有原材料状态
	materialEPCs := make([]string, 0)
	for i := range materials {
		materials[i].Status = "in_transit"
		materials[i].Trans = materials[i].Trans + "->manufacturer"
		materials[i].CheckOutTime = time.Now()

		if err := h.DB.Save(&materials[i]).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "更新原材料状态失败"})
			return
		}
		materialEPCs = append(materialEPCs, materials[i].EPCID)
	}

	// 创建产品
	productEPC := "PROD-" + time.Now().Format("20060102150405")
	product := models.Product{
		EPCID:        productEPC,
		Name:         request.ProductName,
		MaterialEPCs: strings.Join(materialEPCs, ","),
		CreateTime:   time.Now(),
		Trans:        "manufacturer",
		Status:       "produced",
	}

	if err := h.DB.Create(&product).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建产品失败"})
		return
	}

	c.JSON(http.StatusOK, ProductResponse{EPCID: product.EPCID})
}

// GetProduct 获取产品信息
func (h *ManufacturerHandler) GetProduct(c *gin.Context) {
	epcID := c.Param("epc_id")
	var product models.Product

	if err := h.DB.Where("epc_id = ?", epcID).First(&product).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
		return
	}

	c.JSON(http.StatusOK, product)
}

